from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Article, Topic, Comment, User_info
from django.http import HttpResponse, HttpResponseRedirect
from urllib.request import urlretrieve
import os
import hashlib
from PIL import Image

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

'''
伪静态化
'''


def pseudo(request, id):
    dir_path = os.path.join(BASE_DIR, "templates/staticpage/")
    for i in range(0, int(id)):
        try:
            url = "http://127.0.0.1:8000/article/" + str(i)
            urlretrieve(url, filename=dir_path + str(i) + ".html")
        except Exception as err:
            print(err)
    return HttpResponse("完成")


'''
查询文章列表
带分页功能
'''


def home(request):
    topics = Topic.objects.all()
    articles = Article.objects.all()
    hot = [a for a in articles if a.comment_set.count() > 3][:6]
    paginator = Paginator(articles, 6)  # 每页显示6条数据
    page = request.GET.get('page')  # 获取请求的页数
    try:
        articles = paginator.page(page)  # 获取当前页数的数据列表
    except PageNotAnInteger:  # 如果返回的页码不是数字(空值),返回第一页
        articles = paginator.page(1)
    except EmptyPage:  # 如果页数超出范围,返回最后一页
        articles = paginator.page(paginator.num_pages)
    return render(request, "index.html", {"articles": articles,
                                          "hot": hot,
                                          "topics": topics, })


'''
注册用户
'''


def register(request):
    if request.session.has_key("s_name_001"):
        return HttpResponseRedirect("/")
    if request.method == "POST":
        username = request.POST["username"]
        pwd = request.POST["password"]
        email = request.POST["email"]
        nick = request.POST["nickname"]
        phone = request.POST["phone"]
        # MD5加密用户的密码
        hl = hashlib.md5()
        hl.update(pwd.encode(encoding='utf-8'))
        pwd = hl.hexdigest()

        User_info.objects.create(username=username, password=pwd, email=email,
                                 nickname=nick, phone=phone)
        return HttpResponseRedirect("/login")
    return render(request, "register.html")


'''
用户登录
'''


def login(request):
    if request.session.has_key("s_name_001"):
        return HttpResponseRedirect("/")
    if request.method == "POST":
        name = request.POST["username"]
        pwd = request.POST["password"]

        hl = hashlib.md5()
        hl.update(pwd.encode(encoding='utf-8'))
        pwd = hl.hexdigest()

        islogin = User_info.objects.filter(username__exact=name, password__exact=pwd)
        if islogin:
            request.session["s_name_001"] = name
            return HttpResponseRedirect("/")
        else:
            return HttpResponse("登录失败")
    return render(request, "login.html")


'''
用户注销
'''


def logout(request):
    del request.session["s_name_001"]
    return HttpResponseRedirect("/")


'''
根据文章ID,展示文章详细信息
'''


def article(request, id):
    topics = Topic.objects.all()
    path = os.path.join(BASE_DIR, "templates/staticpage/")
    if os.path.exists(path + str(id) + ".html"):
        return render(request, path + str(id) + ".html")
    else:
        cur_article = list(Article.objects.filter(id=id).all())[0]
        tmp_next_list = list(Article.objects.filter(id__gt=id).values("id"))
        tmp_pre_list = list(Article.objects.filter(id__lt=id).values("id"))

        if len(tmp_next_list) == 0:
            nexts = list(Article.objects.filter(id=id).values("id"))[0]
        else:
            nexts = list(Article.objects.filter(id__gt=id).values("id"))[0]

        if len(tmp_pre_list) == 0:
            pres = list(Article.objects.filter(id=id).values("id"))[0]
        else:
            pres = list(Article.objects.filter(id__lt=id).values("id"))[-1]

        return render(request, "detail.html", {"article": cur_article, "topics": topics,
                                               "nexts": nexts, "pres": pres, })


'''
发布文章
'''


def post(request):
    if request.session.has_key('s_name_001') is False:
        return HttpResponseRedirect('/login')
    topics = Topic.objects.values("id", "tname")
    user = list(User_info.objects.filter(username=request.session['s_name_001']).values())[0]
    user_id = user["id"]
    if request.method == "POST":
        content = request.POST["content"]
        tid = request.POST["topic_id"]
        title = request.POST["title"]
        brief = request.POST["brief"]
        topic1 = Topic.objects.get(id=tid)
        article1 = Article(title=title, content=content, brief=brief, topic=topic1)
        article1.save()  # 普通插入的数据和外键插入的数据需要先save()
        article1 = Article.objects.get(title=title)
        article1.author.add(user_id)
        article1.save()

        up_image_name = request.POST["up_image"]
        if up_image_name == "":
            return HttpResponseRedirect("/article/" + str(article1.id))
        photo = request.FILES['up_image']
        if photo:
            photo_name = "upload/" + request.FILES.get('up_image').name
            img = Image.open(photo)
            img.save(BASE_DIR + "/static/userimg/" + photo_name)
            count = Article.objects.filter(id=article1.id).update(image=photo_name)
            if count:
                print("上传成功")
            else:
                print("上传失败")
        return HttpResponseRedirect("/article/" + str(article1.id))

    return render(request, "post.html", {"topic": topics, })


'''
按照话题查询文章列表
'''


def topic(request, id):
    topics = Topic.objects.all()
    articles = Article.objects.filter(topic_id=id).all()
    paginator = Paginator(articles, 10)  # 每页显示6条数据
    page = request.GET.get('page')  # 获取请求的页数
    try:
        articles = paginator.page(page)  # 获取当前页数的数据列表
    except PageNotAnInteger:  # 如果返回的页码不是数字(空值),返回第一页
        articles = paginator.page(1)
    except EmptyPage:  # 如果页数超出范围,返回最后一页
        articles = paginator.page(paginator.num_pages)
    return render(request, "topics.html", {"articles": articles, "topics": topics, })


'''
评论
'''


def comment(request, id):
    commentator = request.POST["commentator"]
    commentator_id = list(User_info.objects.filter(username=commentator).values("id"))[0]["id"]
    content = request.POST["content"]
    Comment.objects.create(content=content, article_id=id, commentator_id=commentator_id)
    return HttpResponseRedirect("/article/"+str(id))


def archive(request):
    return render(request, "archive.html")
